



//
//  SocketManager.swift
//  Client
//
//  Created by 叶情宇 on 2017/7/4.
//  Copyright © 2017年 叶情宇. All rights reserved.
//

import UIKit
import SwiftSocket
class SocketManager: NSObject {
    
    fileprivate var tcpClient :TCPClient
     init(address:String,port:Int32) {
        tcpClient =  TCPClient(address: address, port: port)
    }
}

extension SocketManager{
    func connectToServer() -> Bool {
        let rest = tcpClient.connect(timeout: 5)
        return rest.isSuccess ? true : false
    }
    
    func  sendMessgae(_ text:String) -> Bool {
       return tcpClient.send(string: text).isSuccess
    }
    
    @discardableResult
    func  sendData(_ data:Data,_ type :Int) -> Bool {
        //1.将消息长度写入到data
        var length = data.count
        let headerData = Data(bytes: &length, count: 4)
        //2.消息类型
        var tmpType = type
        let typeData =  Data(bytes: &tmpType, count: 2)
        
        //3.发送消息的总数据
        let totalData = headerData + typeData + data
        //4.发送数据
        return tcpClient.send(data: totalData).isSuccess
    }
}
